// 空文件或删除未使用的导入
import { BusinessError, NetworkError, AuthError } from '../types/api'

/**
 * 统一的错误处理工具
 * 提供标准化的错误处理和用户提示
 */
export class ErrorHandler {
  private static messageInstance: any = null

  /**
   * 设置消息实例（需要在组件中调用）
   */
  static setMessageInstance(message: any): void {
    this.messageInstance = message
  }

  /**
   * 处理错误
   */
  static handleError(error: any, options: ErrorHandleOptions = {}): void {
    const { showMessage = true, defaultMessage = '操作失败' } = options

    let message = defaultMessage
    let type: 'error' | 'warning' | 'info' = 'error'

    if (error instanceof BusinessError) {
      // 业务错误
      message = error.msg || defaultMessage
      if (error.code === 403) {
        type = 'warning'
      }
    } else if (error instanceof NetworkError) {
      // 网络错误
      if (error.status === 0) {
        message = '网络连接失败，请检查网络设置'
      } else if (error.status >= 500) {
        message = '服务器错误，请稍后重试'
      } else {
        message = `请求失败 (${error.status})`
      }
    } else if (error instanceof AuthError) {
      // 认证错误
      message = error.message
      type = 'warning'
    } else if (error instanceof Error) {
      // 其他错误
      message = error.message || defaultMessage
    }

    if (showMessage && this.messageInstance) {
      this.showMessage(message, type)
    }

    // 记录错误日志
    this.logError(error, message)
  }

  /**
   * 显示消息提示
   */
  private static showMessage(message: string, type: 'error' | 'warning' | 'info'): void {
    if (!this.messageInstance) {
      console.warn(`[${type.toUpperCase()}] ${message}`);
      return
    }
    
    try {
      switch (type) {
        case 'error':
          this.messageInstance.error(message)
          break
        case 'warning':
          this.messageInstance.warning(message)
          break
        case 'info':
          this.messageInstance.info(message)
          break
      }
    } catch (error) {
      console.error('Failed to show message:', error);
      console.warn(`[${type.toUpperCase()}] ${message}`)
    }
  }

  /**
   * 记录错误日志
   */
  private static logError(error: any, message: string): void {
    console.error(`[ErrorHandler] ${message}`, {
      error,
      timestamp: new Date().toISOString(),
      userAgent: navigator.userAgent,
      url: window.location.href
    })
  }

  /**
   * 处理表单验证错误
   */
  static handleValidationError(errors: Record<string, string[]>): void {
    const messages = Object.values(errors).flat()
    if (messages.length > 0 && this.messageInstance) {
      this.messageInstance.error(messages[0])
    }
  }

  /**
   * 处理异步操作错误
   */
  static async handleAsyncOperation<T>(
    operation: () => Promise<T>,
    options: AsyncOperationOptions = {}
  ): Promise<T | null> {
    const {
      successMessage,
      errorMessage,
      showSuccessMessage = false,
      showErrorMessage = true
    } = options

    console.log('handleAsyncOperation: 开始执行操作');
    
    try {
      const result = await operation()
      console.log('handleAsyncOperation: 操作成功，结果:', result)
      
      if (showSuccessMessage && successMessage && this.messageInstance) {
        console.log('handleAsyncOperation: 显示成功消息:', successMessage)
        this.messageInstance.success(successMessage)
      } else {
        console.log('handleAsyncOperation: 不显示成功消息，条件检查:', { 
          showSuccessMessage, 
          successMessage, 
          hasMessageInstance: !!this.messageInstance 
        })
      }
      
      return result
    } catch (error) {
      console.log('handleAsyncOperation: 操作失败，错误:', error)
      if (showErrorMessage) {
        this.handleError(error, { defaultMessage: errorMessage })
      }
      return null
    }
  }
}

/**
 * 错误处理选项
 */
interface ErrorHandleOptions {
  showMessage?: boolean
  defaultMessage?: string
}

/**
 * 异步操作选项
 */
interface AsyncOperationOptions {
  successMessage?: string
  errorMessage?: string
  showSuccessMessage?: boolean
  showErrorMessage?: boolean
}

/**
 * 便捷的错误处理函数
 */
export function handleError(error: any, defaultMessage = '操作失败'): void {
  ErrorHandler.handleError(error, { defaultMessage })
}

/**
 * 便捷的异步操作包装函数
 */
export async function handleAsyncOperation<T>(
  operation: () => Promise<T>,
  options: AsyncOperationOptions = {}
): Promise<T | null> {
  return ErrorHandler.handleAsyncOperation(operation, options)
}